<template>
    <div class="mu-img" :style="boxStyle" ref="img">
        <img :src="current_src" draggable="false" ref="img" v-if="loader" />
    </div>
</template>
<script>
    /**
     *  time 2017/03/20
     *  name Spicely
     *  email Spicely@outlook.com
     *  docs
     *      用于提供单个图片加载
     */
    import mixins from '../../../mixins'
    export default {
        name: 'mu-img',
        mixins: [mixins],
        data: function () {
            return {
                loader: false,
                showImg: false,
                current_src: '',
                boxStyle: {
                    width: '',
                    height: ''
                },
                left: 0,
                top: 0,
                width: 0,
                height: 0
            }
        },
        mounted: function () {
            let img = new Image()
            img.onload = this.init
            img.onerror = () => {
                this.$emit('on-error', this.src)
            }
            img.src = this.src
            this.$on('on-client-resize', () => {
                this.initImg()
            })
        },
        props: {
            src: {
                type: String,
                default: ''
            }
        },
        methods: {
            init: function () {
                this.loader = true
                this.current_src = this.src
                this.$emit('on-load', this.src)
                this.$nextTick(() => {
                    this.boxStyle = {
                        height: this.$refs.img.height + 'px',
                        width: this.$refs.img.width + 'px'
                    }
                    this.height = this.$refs.img.height
                    this.width = this.$refs.img.width
                    this.initImg()
                })
            },
            initImg: function () {
                this.left = this.$refs.img.offsetLeft 
                this.top = this.$refs.img.offsetTop
                if (this.left >= 0 && this.left <= this.clientWidth && this.top >= 0 && this.top <= this.clientHeight) {
                    this.showImg = true
                }
            }
        }
    }

</script>
